package com.jwater.core.manager.job;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jwater.core.common.param.ParamMap;
import com.jwater.core.manager.common.conf.WorkerConfParse;
import com.jwater.core.manager.common.model.JobInfo;
import com.jwater.launch.DeployPathUtils;
import com.jwater.launch.LoaderUtils;

import jwater.org.springframework.boot.loader.JWaterSpringbootLauncher;
import jwater.org.springframework.util.StringUtils;

/**
 * @description:job节点
 * @author: jnner
 * @createDate: 2021/2/5
 * @version: 1.0
 */
public class JobNode {
    protected static Logger logger = LoggerFactory.getLogger(JobNode.class);

    private JobInfo jobInfo;
    private long time;

    public JobNode(JobInfo jobInfo, long time) {
        this.jobInfo = jobInfo;
        this.time = time;
    }

    public void start() {
        try {
            loadToClasspath();
            boolean springboot = "true".equals(jobInfo.getProps().getString("springboot", "false"));
            if (springboot) {
                logger.info("spring boot loader run:" + jobInfo.getClassName());
                new JWaterSpringbootLauncher(jobInfo.getClassName()).launch(getMainArgs());
            } else {
                logger.info("run:" + jobInfo.getClassName());
                LoaderUtils.exeMain(jobInfo.getClassName(), getMainArgs());
            }
        } catch (Throwable e) {
            logger.error(e.toString(), e);
        }
    }

    private String[] getMainArgs() {
        String mainArgs = jobInfo.getProps().getString("mainArgs");
        if (StringUtils.isEmpty(mainArgs)) {
            return new String[]{String.valueOf(time)};
        }
        return (mainArgs + " " + time).split("\\s+");
    }

    /**
     * 加载配置文件和jar包到类路径下
     */
    private void loadToClasspath() {
        String regionName = jobInfo.getRegionName();
        String deployName = jobInfo.getDeployName();
        ParamMap props = jobInfo.getProps();
        String jarDir = props.getString("jarDir");
        String confDir = props.getString("confDir");
        String classpathDir = props.getString("classpathDir");
        String include = props.getString("include");
        Long version = jobInfo.getInfoProps().getLong("version");
        logger.info("version:" + version);
        List<String> confPaths = new ArrayList<String>();
        List<String> jarPaths = new ArrayList<String>();
        File deployPath = DeployPathUtils.getDeployPath(regionName, deployName, version);
        if (deployPath != null && deployPath.exists()) {
            jarPaths.add(deployPath.getPath() + "/lib");
            if (!StringUtils.isEmpty(jarDir)) {
                for (String dir : jarDir.split(",")) {
                    jarPaths.add(deployPath.getPath() + "/" + dir);
                }
            }
            confPaths.add(deployPath.getPath() + "/conf");
            if (!StringUtils.isEmpty(confDir)) {
                for (String dir : confDir.split(",")) {
                    confPaths.add(deployPath.getPath() + "/" + dir);
                }
            }
            if (!StringUtils.isEmpty(classpathDir)) {
                for (String dir : classpathDir.split(",")) {
                    confPaths.add(deployPath.getPath() + "/" + dir);
                }
            }
        }
        if (!StringUtils.isEmpty(include)) {
            for (String dir : include.split(",")) {
                File includeDeployPath = WorkerConfParse.getDeployPath(regionName, dir);
                if (includeDeployPath != null && includeDeployPath.exists()) {
                    confPaths.add(includeDeployPath.getPath() + "/conf");
                    jarPaths.add(includeDeployPath.getPath() + "/lib");
                }
            }
        }
        try {
            for (String jarPath : jarPaths) {
                LoaderUtils.addJarDir(new File(jarPath), true);
            }
            for (String confPath : confPaths) {
                LoaderUtils.loadDirToClasspath(new File(confPath));
            }
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }

        logger.info("System--env");
        Map<String, String> env = System.getenv();
        for (Entry<String, String> en : env.entrySet()) {
            if (en.getKey().toString().startsWith("JWATER")) {
                logger.info(en.getKey() + "=" + en.getValue());
            }
        }
        logger.info("System--Properties");
        Map<Object, Object> sysProps = System.getProperties();
        for (Entry<Object, Object> en : sysProps.entrySet()) {
            if (en.getKey().toString().startsWith("JWATER")) {
                logger.info(en.getKey() + "=" + en.getValue());
            }
        }
        List<String> allJars = LoaderUtils.getAllJars();
        for (String allJar : allJars) {
            logger.info(allJar);
        }
    }
}
